package com.crm.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.crm.base.BaseController;
import com.crm.domain.entity.User;
import com.crm.result.Result;
import com.crm.service.UserService;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;
import java.util.Random;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController<UserService, User> {

    // 修改密码
    @RequestMapping("/update-password")
    public Result<Boolean> updPwd(String oldPwd, String newPwd) throws Exception {
        return baseService.updPwd(oldPwd, newPwd) ? Result.success() : Result.failure();
    }

    // 重置密码
    @RequestMapping("/reset-password")
    public Result<Boolean> resetPwd(Integer uId) {
        return Result.success(baseService.resetPwd(uId));
    }


    // 修改用户信息
    @RequestMapping("/update-profile")
    public Result<User> updUsers(@RequestParam(value = "file", required = false) MultipartFile file, User u, HttpServletRequest request) throws Exception {
        // 判断文件是否为空
        if (file != null) {
            // 得到文件名
            String filename = file.getOriginalFilename();

            // 判断文件名是否为空
            if (filename != null) {

                // 得到文件后缀名
                String suffix = filename.substring(filename.lastIndexOf(".") + 1);

                // 判断后缀名是否合法
                if (suffix.toLowerCase().matches("(jpg|png|gif)")) {

                    // 防止文件上传时文件名有重复：当前时间（年月日，时分秒 毫秒)
                    String name = DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN) + new Random().nextInt(100);

                    // 返回web项目下文件夹的完整物理路径(绝对路径)
                    String path = request.getServletContext().getRealPath("static/images/users");

                    // 最后文件路径
                    String filePath = path + "\\" + name + filename.substring(filename.lastIndexOf("."));

                    // 文件上传
                    FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath));

                    System.out.println("文件上传成功~~~");

                    // 设置头像名称
                    u.setUserImg(name + "." + suffix);
                }
            }
        }

        baseService.upd(u);

        // 更新 session 存储的用户信息
        HttpSession session = request.getSession();
        User sessionUser = (User) session.getAttribute("session_user");

        sessionUser.setNickname(u.getNickname());
        sessionUser.setUserEmail(u.getUserEmail());
        sessionUser.setUserImg(u.getUserImg());
        sessionUser.setUserPhone(u.getUserPhone());

        session.setAttribute("session_user", sessionUser);

        return Result.success(u);
    }


    // 查询所有客户经理
    @RequestMapping("/findCustomer")
    public List<User> findCustomer() {
        return baseService.findCustomer();
    }


    // 查询有权限创建营销机会的用户
    @RequestMapping("/findCreateSaleChance")
    public List<User> findCreateSaleChance() {
        return baseService.findCreateSaleChance();
    }
}
